<template>
  <div>
    <Tour v-model:current="current" v-model:show="show" :steps="steps" />
    <!-- <a-button @click="(show = !show) && (current = 0)">开启操作提示</a-button> -->
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" ref="basicTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined" ref="step1"> {{ common('addText') }}</a-button> -->
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                {{ common('delText') }}
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >{{ common('batchOperation') }}
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <template #fileSlot="{ text }">
        <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
        <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <InventoryManageModal ref="inventoryManageModal" @register="registerModal" @success="handleSuccess"></InventoryManageModal>
    <ViewModal @register="registerModal2" :fData="formData"></ViewModal>
    <!-- 查看盘点详情页面 -->
    <div>
      <Modal v-model:visible="open" :title="inventory('inventoryDetail')" @ok="handleOk" style="width: 1000px" centered>
        <BasicTable :dataSource="modalDataSource" :columns="modalColumns" style="height: 500px; padding: 10px"> </BasicTable>
      </Modal>
    </div>
  </div>
</template>

<script lang="ts" name="inventory manage-inventoryManage" setup>
  import { ref, h, onMounted, nextTick } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import InventoryManageModal from './components/InventoryManageModal.vue';
  import { columns, searchFormSchema } from './InventoryManage.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './InventoryManage.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { Modal } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { saveOrUpdate } from './InventoryManage.api';
  import { Tour, type TourStep } from '@/components/Tour/index';
  import ViewModal from './components/ViewModal.vue';
  const { t: asset } = useI18n('asset.assetInfo.fields');
  const { t: tour } = useI18n('asset.assetInfo.tour');
  const { t: common } = useI18n('common');
  const { t: inventory } = useI18n('asset.inventoryManagement.fields');
  //
  const formData = ref({});
  const current = ref(0);
  const step1 = ref();
  const inventoryManageModal = ref<InstanceType<typeof InventoryManageModal>>();
  const basicTable = ref<InstanceType<typeof BasicTable>>();
  const show = ref(false);
  console.log(step1);
  console.log(inventoryManageModal);

  const modalColumns = [
    {
      title: asset('cartegory'),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: asset('code'),
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: asset('name'),
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: asset('position'),
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: inventory('actualPosition'),
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: inventory('count'),
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: inventory('actualCount'),
      dataIndex: 'address',
      key: 'address',
    },

    {
      title: inventory('difference'),
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: inventory('inventoryState'),
      dataIndex: 'address',
      key: 'address',
    },
  ];
  const modalDataSource = [];
  let formParams: null = null;
  //注册model
  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerModal2, { openModal: openModal2 }] = useModal();
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      title: '盘点管理',
      api: list,
      columns,
      canResize: false,
      beforeFetch: (params) => {
        console.log('$$$$ params', params);
        return Object.assign(params, formParams);
      },
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 320,
        fixed: 'right',
      },
    },
    exportConfig: {
      name: '盘点管理',
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;
  //自定义事件
  const open = ref<boolean>(false);
  // const showModal = () => {
  //   open.value = true;
  // };
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    open.value = false;
  };
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
      visualViewport: '是否生成?',
    });
  }
  //生成报告
  function createReport(record: Recordable) {
    Modal.confirm({
      title: inventory('confirmBox'),
      content: inventory('generateReportText'),
      async onOk() {
        // 用户点击确认按钮时的回调函数
        record.inventoryState = '3';
        await saveOrUpdate(record, true);
        reload();
      },
      onCancel() {},
    });
  }
  //查看盘点详情
  // function getInventoryDetail(record: Recordable) {
  //   showModal();
  //   console.log(record);
  // }
  /**
     }
     /**
      * 编辑事件
      */
  function handleEdit(record: Recordable) {
    formData.value = record;
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 编辑状态step
   */

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    formData.value = record;
    console.log(record, 'formData的值啊');
    openModal2(true);
  }
  //废弃事件
  function handleDiscard(record: Recordable) {
    Modal.confirm({
      title: inventory('confirmBox'),
      // content: `确定为盘点"${record.inventoryNumber}"执行废弃操作吗？`,
      content: inventory('discardText'),
      async onOk() {
        // 用户点击确认按钮时的回调函数
        record.checkState = '3';
        await saveOrUpdate(record, true);
        reload();
      },
      onCancel() {
        // 用户点击取消按钮时的回调函数
      },
      centered: true,
    });
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  //确认事件

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    const num = {
      view: {
        label: inventory('view'),
        onClick: handleDetail.bind(null, record),
      },
      createReport: {
        label: inventory('finish'),
        onClick: createReport.bind(null, record),
      },
    };

    if (['0', '2', '4'].includes(record.inventoryState)) {
      return [num.view];
    } else if (record.inventoryState === '3') {
      return [num.view, num.createReport];
    }
  }
  //步骤
  const steps = ref<TourStep[]>([
    {
      el: () => step1.value.$el,
      title: common('addText'),
      message: tour('step1Msg'),
      next: (next) => {
        handleAdd();
        nextTick(() => {
          next();
        });
      },
    },
    {
      el: () => inventoryManageModal.value?.basicForm?.$el,
      title: common('addText'),
      message: h('div', {}, [tour('step2Msg1'), h('span', { style: 'color:red;' }, ' * '), tour('step2Msg2')]),
      prev: (prev) => {
        closeModal();
        prev();
      },
    },
    {
      el: () => inventoryManageModal.value?.basicModal?.modalFooter?.$el,
      title: tour('step3Title'),
      message: tour('step3Msg'),
      next: (next) => {
        closeModal();
        next();
      },
    },
    {
      el: () => basicTable.value?.tableElRef?.$el,
      title: inventory('inventoryList'),
      message: tour('step4Msg'),
      prev: (prev) => {
        handleAdd();
        nextTick(() => {
          prev(700);
        });
      },
    },
  ]);
  onMounted(() => {
    console.log(basicTable.value?.tableElRef?.$el);

    setTimeout(() => {
      show.value = false;
    }, 200);
  });
</script>

<style scoped>
  .alldashedBorder {
    width: 900px;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    color: #000;
    padding: 10px;
  }
  .dashedBorder {
    display: inline-block;
    height: 25px;
    width: 130px;
    border-bottom: 1px dashed #ada4a4;
    padding-bottom: 5px;
    margin-left: 10px;
    text-align: center;
  }
</style>
